package com.zut.edu;

import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Toast;

import androidx.annotation.DrawableRes;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSON;
import com.qmuiteam.qmui.layout.QMUILinearLayout;
import com.qmuiteam.qmui.skin.QMUISkinManager;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView;
import com.qmuiteam.qmui.widget.dialog.QMUIBottomSheet;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;
import com.zut.edu.bean.Company;
import com.zut.edu.bean.Page;
import com.zut.edu.bean.User;
import com.zut.edu.http.BaseCallback;
import com.zut.edu.http.OkhttpHelper;
import com.zut.edu.utils.CameraUtils;
import com.zut.edu.utils.StringUtils;

import org.jetbrains.annotations.NotNull;

import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import okhttp3.Call;
import okhttp3.Response;

public class RegisterThirdActivity extends AppCompatActivity implements View.OnClickListener{
    private static final int PHOTORESULT = 3;
    @BindView(R.id.register_third_button)
    QMUIRoundButton registerthirdbutton;
    @BindView(R.id.reg_company_text)
    EditText registercompanytext;
    @BindView(R.id.reg_name_text)
    EditText registernametext;
    @BindView(R.id.reg_password_text)
    EditText registerpasswordtext;
    @BindView(R.id.reg_identity_text)
    EditText registeridentitytext;

    @BindView(R.id.register_userhead)
    QMUIRadiusImageView registeruserhead;
    @BindView(R.id.registerthird_back)
    ImageView registerthirdback;



    @BindView(R.id.reg_name_layout)
    QMUILinearLayout regnamelayout;
    @BindView(R.id.reg_password_layout)
    QMUILinearLayout regpasswordlayout;
    @BindView(R.id.reg_company_layout)
    QMUILinearLayout regcompanylayout;
    @BindView(R.id.reg_identity_layout)
    QMUILinearLayout regidentitylayout;

    Object[] hash = new Object[2];
    int identity=0;
    private List<Company> companyList = new ArrayList<>();
    private String phone;
    private String companyId;
    private String filePath;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_registerthird);
        ButterKnife.bind(this);
        setListener();
        initCompanyList();
        QMUIStatusBarHelper.translucent(this);//沉浸式
        QMUIStatusBarHelper.setStatusBarLightMode(this);
        CameraUtils.initRadiusImageView(registeruserhead,R.mipmap.camera);
        EditLayout();
        RegisterSecondActivity.instance.finish();
        Intent intent = getIntent();
        if(intent!=null)phone =intent.getStringExtra("phone");
    }
    private void setListener(){
        registerthirdbutton.setOnClickListener(this);
        registerthirdbutton.setChangeAlphaWhenPress(true);
        registercompanytext.setOnClickListener(this);
        registeridentitytext.setOnClickListener(this);
        registerthirdback.setOnClickListener(this);
        registeruserhead.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.register_third_button:
                if(TextUtils.isEmpty(registernametext.getText().toString().trim())){
                    Toast.makeText(this,  "填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(registerpasswordtext.getText().toString().trim())){
                    Toast.makeText(this,  "填写密码", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(TextUtils.isEmpty(registercompanytext.getText().toString().trim())){
                    Toast.makeText(this,  "选择你的公司", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(identity==0){
                    Toast.makeText(this,  "选择你的职位", Toast.LENGTH_SHORT).show();
                    return;
                }
                if(hash[1]==null){
                    Toast.makeText(this,  "选择你的头像", Toast.LENGTH_SHORT).show();
                    return;
                }
                try {
                    uploadimg(new File(filePath),phone,registerpasswordtext.getText().toString().trim(),registernametext.getText().toString().trim(),String.valueOf(identity),companyId);
                }
                catch (Exception e){
                    Log.e("ER",String.valueOf(e));
                }
                break;
            case R.id.reg_company_text:
                showCompanyList(
                        true, true, false, "选择你的公司",
                        100, true, false);
                break;
            case R.id.reg_identity_text:
                showIdentitySheet();
                break;
            case R.id.registerthird_back:
                super.onBackPressed();
                break;
            case R.id.register_userhead:
                CameraUtils.startPhotoAlbum(RegisterThirdActivity.this);
                break;
        }
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {//实时监听,多次执行,分类requestCode,判断handleResultFromCameraOrPhotos
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==PHOTORESULT) {
            hash = CameraUtils.handleResultFromCameraOrPhotos(RegisterThirdActivity.this, requestCode, resultCode, data);
            if (hash != null) {
                filePath = (String) hash[0];
                registeruserhead.setImageBitmap((Bitmap) hash[1]);
            }
        }
        else CameraUtils.handleResultFromCameraOrPhotos(RegisterThirdActivity.this,requestCode,resultCode,data);

    }
    private void showCompanyList(boolean gravityCenter,
                                           boolean addCancelBtn,
                                           boolean withIcon,
                                           CharSequence title,
                                           int itemCount,
                                           boolean allowDragDismiss,
                                           boolean withMark) {
        QMUIBottomSheet.BottomListSheetBuilder builder = new QMUIBottomSheet.BottomListSheetBuilder(this);
        builder.setGravityCenter(gravityCenter)
                .setSkinManager(QMUISkinManager.defaultInstance(this))
                .setTitle(title)
                .setAddCancelBtn(addCancelBtn)
                .setAllowDrag(allowDragDismiss)
                .setNeedRightMark(withMark)
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        dialog.dismiss();
                        registercompanytext.setText(companyList.get(position).getCompanyName());
                        companyId = companyList.get(position).getCompanyId();
                    }
                });
        if(withMark){
            builder.setCheckedIndex(40);
        }
        for (int i = 0; i < companyList.size(); i++) {
            builder.addItem(companyList.get(i).getCompanyName());
        }
        builder.build().show();
    }

    private void showIdentitySheet() {
        new QMUIBottomSheet.BottomListSheetBuilder(this)
                .addItem("管理人员")
                .addItem("操作人员")
                .setSkinManager(QMUISkinManager.defaultInstance(this))
                .setOnSheetItemClickListener(new QMUIBottomSheet.BottomListSheetBuilder.OnSheetItemClickListener() {
                    @Override
                    public void onClick(QMUIBottomSheet dialog, View itemView, int position, String tag) {
                        switch (position) {
                            case 0:
                                identity = position+1;
                                registeridentitytext.setText("管理人员");
                                break;
                            case 1:
                                identity = position+1;
                                registeridentitytext.setText("操作人员");
                                break;
                        }
                        dialog.dismiss();
                    }
                })
                .build().show();
    }

    private void finalRegister(String userAccount,String userPassword,String userName,String userIdentity,String companyId,String userPhoto){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        Map<String,Object> params = new HashMap<>(6);
        params.put("userAccount",userAccount);
        params.put("userPassword",userPassword);
        params.put("userName",userName);
        params.put("userIdentity",userIdentity);
        params.put("companyId",companyId);
        params.put("userPhoto",userPhoto);
        okhttpHelper.post(StringUtils.BASE_URL+"/user/register",params, new BaseCallback<User>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("login_onFailure",e.getMessage());
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, User user, int code) throws IOException {
                switch (code){
                    case 0:
                        Toast.makeText(RegisterThirdActivity.this,"注册成功",Toast.LENGTH_LONG).show();
                        Intent login = new Intent(RegisterThirdActivity.this,LoginActivity.class);
                        startActivity(login);
                        break;
                    case 1001:
                        Toast.makeText(RegisterThirdActivity.this,"该账户已被注册",Toast.LENGTH_LONG).show();
                        Intent re = new Intent(RegisterThirdActivity.this,RegisterFirstActivity.class);
                        re.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
                        re.putExtra("type","register");
                        startActivity(re);
                        break;
                    default:
                        Toast.makeText(RegisterThirdActivity.this,"注册失败,请重试",Toast.LENGTH_LONG).show();
                        break;
                }
                Log.e("http_response",code+":"+response.message());
            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("login_onError",e.getMessage());
            }
        });
    }
    private void initCompanyList(){
        OkhttpHelper okhttpHelper = OkhttpHelper.getInstance();
        okhttpHelper.get(StringUtils.BASE_URL + "/company/queryAll",null, new BaseCallback<Page<Company>>() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.e("F",String.valueOf(e));
            }

            @Override
            public void onSuccess(@NotNull Call call, @NotNull Response response, Page<Company> companyPage, int code) throws IOException {
                Log.e("R",response.message());
                companyList = companyPage.getList();
            }

            @Override
            public void onError(@NotNull Call call, @NotNull Response response, int code, Exception e) {
                Log.e("E",String.valueOf(code));
                if(e!=null) Log.e("e", String.valueOf(e));
            }
        });

    }

    public void uploadimg(File file, final String userAccount, final String userPassword, final String userName, final String userIdentity, final String companyId)
    {
        if (!file.exists())
        {
            Toast.makeText(RegisterThirdActivity.this, "文件不存在，请修改文件路径", Toast.LENGTH_SHORT).show();
            return;
        }
        String ts = String.valueOf(System.currentTimeMillis());
        String id = "28564";
        String token = "537a3999d5d343a4be5449b964a88106";
        String sign = null;
        try {
            sign = StringUtils.MD5(id+"-"+token+"-"+ts);
        } catch (Exception e) {
            e.printStackTrace();
        }
        Log.e("MD5",sign);
        Map<String, String> params = new HashMap<>();
        params.put("id",id);
        params.put("ts",ts);
        params.put("sign",sign);
        OkHttpUtils.post()//
                .addFile("image", id+ts, file)//
                .url("https://api.superbed.cn/upload")
                .params(params)//
                .build()//
                .execute(new Callback() {
                    @Override
                    public Object parseNetworkResponse(Response response, int id) throws Exception {
                        String resultStr = response.body().string();
                        String userPhoto = JSON.parseObject(resultStr).getString("url");
                        finalRegister(userAccount,userPassword,userName,userIdentity,companyId,userPhoto);
                        Log.e("body",resultStr);
                        return null;
                    }

                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Log.e("UserHead_E",String.valueOf(e));
                    }

                    @Override
                    public void onResponse(Object response, int id) {
                    }
                });
    }

    private void EditLayout(){
        regnamelayout.setBorderColor(getResources().getColor(R.color.qmui_config_color_black));
        regnamelayout.setBorderWidth(1);
        regnamelayout.setRadius(25);

        regpasswordlayout.setBorderColor(getResources().getColor(R.color.qmui_config_color_black));
        regpasswordlayout.setBorderWidth(1);
        regpasswordlayout.setRadius(25);

        regcompanylayout.setBorderColor(getResources().getColor(R.color.qmui_config_color_black));
        regcompanylayout.setBorderWidth(1);
        regcompanylayout.setRadius(25);

        regidentitylayout.setBorderColor(getResources().getColor(R.color.qmui_config_color_black));
        regidentitylayout.setBorderWidth(1);
        regidentitylayout.setRadius(25);
    }


}
